package com.vogue.supplymall.order.domain.service.impl;


import com.vogue.ssm.database.entity.SnowflakeIdWorker;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.account.domain.model.User;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.CommentInfo;
import com.vogue.supplymall.order.domain.dao.CommentDao;
import com.vogue.supplymall.order.domain.model.CommentDetail;
import com.vogue.supplymall.order.domain.service.CommentDetailService;
import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.supplymall.shop.domain.service.OrganShopImgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("commentDetailService")
public class CommentDetailServiceImpl extends BaseServiceImpl<CommentDetail, Long> implements CommentDetailService {

    @Resource
    private CommentDao commentDao;
    @Resource
    private OrganShopImgService organShopImgService;
    @Resource
    private UserService userService;


    public CommentDetailServiceImpl(BaseDao<CommentDetail, Long> baseDao) {
        super(baseDao);
    }

    @Override
    public List<Map<String, Object>> findBuyerCommentDetail(CommentInfo commentInfo) {
        List<Map<String, Object>> detail = commentDao.findBuyerCommentDetail(commentInfo);

        for (Map<String, Object> m : detail) {
            String shopid = m.get("shopid").toString();
            String commentid = m.get("commentid").toString();
            String commentDetailid = m.get("commentdetailid").toString();
            //获取评价照片
            List<Map<String, Object>> list = commentDao.getProductImgUrls(commentid, commentDetailid);
            if (list == null || list.size() <= 0) {
                m.put("imgUrl", "");
            } else {
                m.put("imgUrl", list);
            }
            //获取门店图片
            String imgurl = organShopImgService.getImgUrl4Comment(shopid);
            if (imgurl == null) {
                m.put("shopimgurl", "");
            } else {
                m.put("shopimgurl", imgurl);
            }
        }
        return detail;
    }

    @Override
    public List<Map<String, Object>> findSellerCommentDetail(CommentInfo commentInfo) {
        List<Map<String, Object>> detail = commentDao.findSellerCommentDetail(commentInfo);

        for (Map<String, Object> m : detail) {
            String shopid = m.get("shopid").toString();
            String commentid = m.get("commentid").toString();
            String commentDetailid = m.get("commentdetailid").toString();
            Long buyerid = Long.valueOf(m.get("buyerid").toString());
            Long burersyscodeid = Long.valueOf(m.get("burersyscodeid").toString());
            //获取评价照片
            List<Map<String, Object>> list = commentDao.getProductImgUrls(commentid, commentDetailid);
            if (list == null || list.size() <= 0) {
                m.put("imgUrl", "");
            } else {
                m.put("imgUrl", list);
            }
            //获取门店图片
            String imgurl = organShopImgService.getImgUrl4Comment(shopid);
            if (imgurl == null) {
                m.put("shopimgurl", "");
            } else {
                m.put("shopimgurl", imgurl);
            }
            //获取买家头像和电话
            User user = userService.getUserById(buyerid, burersyscodeid);
            if (user !=null) {
                m.put("headimgurl",user.getHeadimgurl()==null ? "":user.getHeadimgurl());
                m.put("tel",user.getTel()==null ? "":user.getTel());
            } else {
                m.put("headimgurl","");
                m.put("tel","");
            }
        }
        return detail;
    }

    /**
     * insert comment comment_detail
     * update order_item_product commentstate
     */
    @Override
    @Transactional
    public void updateCommentText() {

        String SELECT_ORDER_CANCEL_SQL = "SELECT o.tendid,"
                    + "o.id orderid,o.ordernumber,o.createdate orderdate,"
                    + "os.shopid,os.shopname,"
                    + "p.productid,p.pname productname,p.imgurl productimgurl,"
                    + "ob.id buyerid,ob.buyername,ob.syscodeid burersyscodeid,os.syscodeid sellersyscodeid,"
                    + "p.id orderitemproductid "
                + "FROM "
                    + "order_item_product p,"
                    + "`order` o,"
                    + "order_seller os,"
                    + "order_buyer ob,"
                    + "order_status ost "
                + "WHERE p.commentstate = 0 "
                    + "AND p.disabledflag = 0 "
                    + "AND o.id = p.orderid "
                    + "AND o.id = os.orderid "
                    + "AND ost.orderstatus = 4 "
                    + "AND ost.orderid = o.id "
                    + "AND o.id = ob.orderid "
                    + "AND TIMESTAMPDIFF(SECOND,o.createdate,now()) >=  (" + ConstantBean.COMMENT_DEFAULT_TIME.longValue() + ") ";

        DealStatus.kacha();
        List<Map<String, Object>> list = commentDao.query(SELECT_ORDER_CANCEL_SQL);

        //insert 表 comment、comment_detail
        StringBuilder commentStr = new StringBuilder("INSERT INTO comment (`id`, `tendid`, `orderid`, `ordernumber`,`orderdate`, ")
                .append("`shopid`, `shopname`, `productid`, `productname`, `productimgurl`, `commentmark`, ")
                .append("`buyerid`, `buyername`, `burersyscodeid`, `sellersyscodeid`, ")
                .append("`hiddenflag`, `restoreflag`,`answerflag`, `createdate`, `modifydate`) VALUES ");

        StringBuilder detailStr = new StringBuilder("INSERT INTO comment_detail (`id`, `tendid`, `commentid`, `commenttext`, ")
                .append("`commentobejct`, `readflag`, `answerflag`, `defaultanswerflag`, `createdate`, `modifydate`) VALUES ");

        //要修改的单据明细id
        StringBuilder orderitemproductids = new StringBuilder();

        long commentId = 0L;//comment的id
        for (Map<String, Object> map : list) {
            commentId = SnowflakeIdWorker.getIns().nextId();
            commentStr.append("(").append(commentId).append(",")
                    .append(map.get("tendid")).append(",")
                    .append(map.get("orderid")).append(",'")
                    .append(map.get("ordernumber")).append("','")
                    .append(map.get("orderdate")).append("',")
                    .append(map.get("shopid")).append(",'")
                    .append(map.get("shopname")).append("',")
                    .append(map.get("productid")).append(",'")
                    .append(map.get("productname")).append("','")
                    .append(map.get("productimgurl")).append("',10,")
                    .append(map.get("buyerid")).append(",'")
                    .append(map.get("buyername")).append("',")
                    .append(map.get("burersyscodeid")).append(",")
                    .append(map.get("sellersyscodeid"))
                    .append(",0,0,0,now(),now())").append(",");

            detailStr.append("(").append(SnowflakeIdWorker.getIns().nextId()).append(",")
                    .append(map.get("tendid")).append(",")
                    .append(commentId).append(",'")
                    .append(ConstantBean.COMMENT_DEFAULT_GOODANSWER)
                    .append("',0,0,0,1,now(),now())").append(",");

            orderitemproductids.append(map.get("orderitemproductid")).append(",");
        }
        String sql = null;
        if (list != null && list.size() > 0) {
            sql = commentStr.substring(0, commentStr.length() - 1) + ";";
            DealStatus.kacha();
            commentDao.update(sql);
            sql = detailStr.substring(0, detailStr.length() - 1) + ";";
            DealStatus.kacha();
            commentDao.update(sql);
        }
        String ids = orderitemproductids.substring(0, orderitemproductids.length() - 1);
        DealStatus.kacha();
        String updateSql = "UPDATE order_item_product SET commentstate = 1 where commentstate = 0 and id in (" + ids + ");";
        commentDao.update(updateSql);
    }

}
